package cn.fastoo.web.api.controller.user;

import cn.fastoo.common.dao.*;
import cn.fastoo.common.entity.*;
import cn.fastoo.common.sampleframe.SFBeanUtils;
import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.utils.Constant;
import cn.fastoo.service.UserService;
import cn.fastoo.common.utils.RegexUtils;
import cn.fastoo.web.dto.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hp on 2017/7/31.
 */

@Controller
@RequestMapping("/v1/admin")
public class AdminController {

    private static Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private UserIplistDao userIplistDao;
    @Autowired
    private UserAccountDao userAccountDao;
    @Autowired
    private UserBalanceRemindDao userBalanceRemindDao;
    @Autowired
    private BlacklistDao blacklistDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @RequestMapping("getUserAccounts")
    @ResponseBody
    public String getAccounts(UserBase userBase) {
        JSONObject jsonObject = new JSONObject();
        List<UserAccount> userAccounts = userAccountDao.find(new Search().addSearchFilter("EQ_userBaseId",userBase.getId()));
        //包装userAccount数据
        List<UserAccountDto> userAccountDtos = new ArrayList<UserAccountDto>();
        for (UserAccount ua:userAccounts) {
            userAccountDtos.add(SFBeanUtils.injectByObject(new UserAccountDto(),ua));
        }
        jsonObject.put("userAccounts",userAccountDtos);
        return new JsonResult(0,"ok",jsonObject).toJson();
    }

    @RequestMapping("getUserBalance")
    @ResponseBody
    public String getUserBalance(UserBase userBase) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("balance",userBase.getBalance());
        return new JsonResult(0,"ok",jsonObject).toJson();
    }


    @RequestMapping("getBalanceRemindInfo")
    @ResponseBody
    public String getBalanceRemindInfo(UserBase userBase) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("loginName",userBase.getLoginName());
        jsonObject.put("remindBalance","");
        jsonObject.put("startTime","");
        jsonObject.put("endTime","");
        UserBalanceRemind remind = userBalanceRemindDao.findOne(new Search().addSearchFilter("EQ_userBaseId",userBase.getId()));
        if (remind!=null) {
            String remindRangTime = remind.getRemindRangeTime();
            jsonObject.put("remindBalance",remind.getRemindBalance());
            jsonObject.put("startTime",remindRangTime.split("-")[0]);
            jsonObject.put("endTime",remindRangTime.split("-")[1]);
        }
        return new JsonResult(0,"ok",jsonObject).toJson();
    }

    @RequestMapping("getUserInfo")
    @ResponseBody
    public String getUserInfo(UserBase userBase){
        UserInfoDto userInfo = new UserInfoDto();
        SFBeanUtils.injectByObject(userInfo,userBase);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userInfo",userInfo);
        return new JsonResult(0,"ok",jsonObject).toJson();
    }

    @RequestMapping("setBalanceRemind")
    @ResponseBody
    public String setBalanceRemind(UserBase userBase,
                                   @RequestParam Double remindBalance,
                                   @RequestParam String startTime,
                                   @RequestParam String endTime){
        return userService.setUserBalanceRemind(remindBalance,startTime,endTime,userBase.getId());
    }

    /**
     * 	apiKeys
     */
    @RequestMapping(value = "apiKeys")
    @ResponseBody
    public String apiKeys(UserBase userBase,String searchApiKey){
        Search search = new Search();
        search.addSearchFilter("EQ_userBaseId",userBase.getId());
        if (StringUtils.isNotBlank(searchApiKey)) {
            search.addSearchFilter("LIKE_apiKey",searchApiKey);
        }
        List<UserAccount> userAccounts = userAccountDao.find(search);
        //包装apiKeys数据
        List<UserApiKeyDto> userApiKeyDtos = new ArrayList<UserApiKeyDto>();
        for (UserAccount userAccount:userAccounts) {
            userApiKeyDtos.add(SFBeanUtils.injectByObject(new UserApiKeyDto(),userAccount));
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userApiKeys",userApiKeyDtos);
        return new JsonResult(0,"ok",jsonObject).toJson();
    }

    /**
     * 	apiKeys生成
     */
    @RequestMapping(value = "apiKeys/save")
    @ResponseBody
    public String saveApiKeys(UserBase userBase){
        List<UserAccount> userAccounts = userAccountDao.find(new Search().addSearchFilter("EQ_userBaseId",userBase.getId()));
        if (userAccounts.size()>=10) {
            return JsonResult.create(400,"apiKey最多只能有10个");
        }
        UserAccount userAccount = new UserAccount();
        userAccount.setUserBaseId(userBase.getId());
        userAccount.setApiKey(UUID.randomUUID().toString().replace("-",""));
        userAccountDao.insert(userAccount);
        return JsonResult.success("添加成功");
    }

    /**
     * 	apiKeys保存dr
     */
    @RequestMapping(value = "apiKeys/saveDr")
    @ResponseBody
    public String saveDr(Long userAccountId,String drUrl){
        Integer isEnable = 0;
        //验证drUrl
        if (StringUtils.isNotBlank(drUrl)) {
            //验证是否合法
            if (!RegexUtils.checkURL(drUrl)) {
                return JsonResult.create(400,"请输入合法Dr地址");
            }
            isEnable = 1;
        }
        UserAccount userAccount = userAccountDao.findById(userAccountId);
        if (userAccount==null) {
            return JsonResult.create(400,"非法访问");
        }
        userAccount.setNeedDr(isEnable);
        userAccount.setDrUrl(drUrl);
        userAccountDao.update(userAccount);
        return JsonResult.success("保存成功");
    }

    /**
     * 删除apiKeys
     */
    @RequestMapping(value = "apiKeys/del")
    @ResponseBody
    public String delApiKeys(UserBase userBase,@RequestParam Long userAccountId) {
        try {
            List<UserAccount> userAccounts = userAccountDao.find(new Search().addSearchFilter("EQ_userBaseId",userBase.getId()));
            if (userAccounts.size()==1) {
                return JsonResult.create(400,"禁止删除");
            }
            userAccountDao.delete(userAccountId);
            return JsonResult.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.create(400,"非法访问");
    }

    /**
     * 	IP白名单UI
     */
    @RequestMapping(value = "iplist")
    @ResponseBody
    public String iplist(UserBase userBase,String ip){
        Search search = new Search();
        search.addSearchFilter("EQ_userBaseId",userBase.getId());
        if (StringUtils.isNotBlank(ip)) {
            search.addSearchFilter("EQ_ip",ip);
        }
        List<UserIplist> userIplists = userIplistDao.find(search);
        //包装userAccount数据
        List<UserIplistDto> userIplistDtos = new ArrayList<UserIplistDto>();
        for (UserIplist userIplist:userIplists) {
            userIplistDtos.add(SFBeanUtils.injectByObject(new UserIplistDto(),userIplist));
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userIplists",userIplistDtos);
        return new JsonResult(0,"ok",jsonObject).toJson();
    }

    /**
     * 	IP白名单保存
     */
    @RequestMapping(value = "iplist/save")
    @ResponseBody
    public String savewhitelist(UserBase userBase,String ip,String remark){
        if (StringUtils.isNotBlank(ip)) {
            if (RegexUtils.checkIpAddress(ip)) {
                UserIplist userIplist = userIplistDao.findOne(new Search().addSearchFilter("EQ_userBaseId",userBase.getId()).addSearchFilter("EQ_ip",ip));
                if (userIplist != null) {
                    userIplist.setIp(ip);
                    userIplist.setRemark(remark);
                    userIplistDao.update(userIplist);
                    return JsonResult.success("保存成功");
                } else {
                    userIplist = new UserIplist();
                    userIplist.setIp(ip);
                    userIplist.setRemark(remark);
                    userIplist.setUserBaseId(userBase.getId());
                    userIplistDao.insert(userIplist);
                    return JsonResult.success("保存成功");
                }
            }
        }
        return JsonResult.create(400,"ip地址格式错误");
    }

    /**
     * 删除ip白名单
     */
    @RequestMapping(value = "iplist/del")
    @ResponseBody
    public String deliplist(@RequestParam Long delid) {
        try {
            userIplistDao.delete(delid);
            return JsonResult.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.create(400,"非法访问");
    }


    /**
     * 	开启关闭IP白名单
     */
    @RequestMapping(value = "iplist/switch")
    @ResponseBody
    public String iplistswitch(UserBase userBase,Integer on){
        userBase.setIpEnable(on);
        userBaseDao.update(userBase);
        return JsonResult.success("设置成功");
    }


    /**
     * 黑名单列表
     */
    @RequestMapping(value = "blacklist")
    @ResponseBody
    public String blacklist(UserBase userBase,Integer pageNo,String keyword){
        pageNo = pageNo ==null ? 0 : pageNo;
        Search search = new Search();
        search.addSearchFilter("EQ_userBaseId",userBase.getId());
        if (StringUtils.isNotBlank(keyword)) {
            search.addSearchFilter("SELF_SQL","phone like '%"+keyword+"%' or user_name like '%"+keyword+"%'");
        }

        search.addPageRequest(new PageRequest(pageNo,10,new Sort(Sort.Direction.DESC,"id")));
        Page<BlackList> page = blacklistDao.findPage(search);


        //包装recharge数据
        List<BlackListDto> blackListDtos = new ArrayList<BlackListDto>();
        List<BlackList> list = page.getContent();
        for (BlackList blackList:list) {
            blackListDtos.add(SFBeanUtils.injectByObject(new BlackListDto(),blackList));
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("blackList",blackListDtos);
        jsonObject.put("totalElements",page.getTotalElements());
        jsonObject.put("size",page.getSize());
        jsonObject.put("totalPages",page.getTotalPages());
        return new JsonResult(0,"ok",jsonObject).toJson();
    }


    /**
     * 	添加黑名单
     */
    @RequestMapping(value = "blacklist/save")
    @ResponseBody
    public String saveblacklist(UserBase userBase,@RequestParam String phone,  String userName,Long blacklistId){
        Pattern pattern1 = Pattern.compile("\\d+\\s+\\d+");
        Pattern pattern2 = Pattern.compile("\\d+");
        Matcher mc1 = pattern1.matcher(phone);
        Matcher mc2 = pattern2.matcher(phone);
        if (mc1.matches()||mc2.matches()) {
            if (mc1.matches()) {
                phone = phone.replaceAll("\\s+", "");
            }
            try {
                if (blacklistId != null) {
                    jdbcTemplate.update("UPDATE IGNORE blacklist SET phone = ? , user_name = ? WHERE id = ?",phone,userName,blacklistId);
                } else {
                    jdbcTemplate.execute("insert IGNORE into blacklist(phone,user_name,user_base_id) values ('" + phone + "','" + userName +"',"  + userBase.getId()+ ")");
                }
            } catch (DataAccessException e) {
                e.printStackTrace();
                return JsonResult.success("保存失败");
            }
            return JsonResult.success("保存成功");
        }
        return JsonResult.create(400,"手机号码格式错误");
    }

    /**
     * 删除黑名单
     */
    @RequestMapping(value = "blacklist/del")
    @ResponseBody
    public String delblacklist(@RequestParam Long blacklistId) {
        try {
            blacklistDao.delete(blacklistId);
            return JsonResult.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.create(101,"删除失败");
    }

    /**
     * 修改用户信息
     */
    @RequestMapping(value = "user/updateinfo")
    @ResponseBody
    public String updateinfo(UserBase userBase, Integer userType,String company,String industry
            ,String businessLicence,String businessLicenceImg,String realName,String idcard,String idcardImg) {
        if (userType!=null&&userType== Constant.UserType.Company.getValue()) {
            userBase.setCompany(company);
            userBase.setIndustry(industry);
            userBase.setBusinessLicence(businessLicence);
            userBase.setBusinessLicenceImg(businessLicenceImg);
            userBase.setUserType(userType);
            userBaseDao.update(userBase);
        }else if (userType!=null&&userType==Constant.UserType.Person.getValue()) {
            userBase.setRealName(realName);
            userBase.setIdcard(idcard);
            userBase.setIdcardImg(idcardImg);
            userBase.setUserType(userType);
            userBaseDao.update(userBase);
        }
        return JsonResult.success("保存成功");
    }

    /**
     * 密码修改
     */
    @RequestMapping(value = "user/changepwd")
    @ResponseBody
    public String changepwd(UserBase userBase,@RequestParam String oldpwd,@RequestParam String newpwd) {
        if (!userBase.getPassword().equals(DigestUtils.sha256Hex(oldpwd))) {
            return JsonResult.create(201,"原密码输入错误");
        }
        userBase.setPassword(DigestUtils.sha256Hex(newpwd));
        userBaseDao.update(userBase);
        return JsonResult.success("保存成功");
    }

}
